package cn.moukou.tongji.ihealth.patient.service;

import cn.moukou.tongji.ihealth.patient.dao.DoctorMapper;
import cn.moukou.tongji.ihealth.patient.pojo.Doctor;
import com.alibaba.fastjson.JSON;
import com.aliyuncs.utils.StringUtils;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class DoctorService {

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    DoctorMapper doctorMapper;

    @Autowired
    RedissonClient redissonClient;

    public Doctor getOneDoctor(String did) {
        return doctorMapper.selectById(did);
    }

    public List<Doctor> getDoctors() {

        String doctorListJson = redisTemplate.opsForValue().get("doctorList");
        if(!StringUtils.isEmpty(doctorListJson)) {
            return JSON.parseArray(doctorListJson, Doctor.class);
        }

        RLock lock = this.redissonClient.getLock("doctorListLock");
        lock.lock();

        String doctorListJson2 = redisTemplate.opsForValue().get("doctorList");
        if(!StringUtils.isEmpty(doctorListJson2)) {
            lock.unlock();
            return JSON.parseArray(doctorListJson2, Doctor.class);
        }

        List<Doctor> doctors = doctorMapper.selectList(null);
        redisTemplate.opsForValue().set("doctorList", JSON.toJSONString(doctors), 7, TimeUnit.DAYS);
        lock.unlock();
        return doctors;
    }

}
